package fitness

import (
	"fitness/internal/entity"
	"fitness/internal/entity/fitness"
	"fitness/pkg/utils"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"time"
)

type UserDao struct {
	DB  *gorm.DB
	Log *zap.Logger
}

func NewUserDao(db *gorm.DB, logger *zap.Logger) *UserDao {
	return &UserDao{
		DB:  db,
		Log: logger,
	}
}

// 根据openid查询用户信息
func (d *UserDao) QueryFitnessUser(openid *string) (fitness.User, error) {
	var user fitness.User
	err := d.DB.Model(&fitness.User{}).Where("openid = ?", *openid).First(&user).Error
	return user, err
}

// 保存用户信息
func (d *UserDao) CreateFitnessUser(openid *string) (fitness.User, error) {
	user := fitness.User{
		Model: entity.Model{
			CreateTime: time.Now(),
		},
		Openid: openid,
	}
	err := d.DB.Create(&user).Error
	return user, err
}

// 修改用户头像
func (d *UserDao) UpdateAvatar(id uint64, filepath string) error {
	err := d.DB.Model(&fitness.User{}).
		Where("id = ? ", id).
		Update("avatar", filepath).Error
	return err
}

func (d *UserDao) GetUserPage(queryParams fitness.MpUserPageQuery) (utils.Page[fitness.User], error) {
	sql := `SELECT
            t1.*
        FROM
            fitness_user t1 `

	where := ""
	if queryParams.PageQuery.Keywords != nil && *queryParams.PageQuery.Keywords != "" {
		where = ` where  
		          t1.mobile LIKE '%` + *queryParams.PageQuery.Keywords + `%'
		           OR t1.username LIKE '%` + *queryParams.PageQuery.Keywords + `%'
		           `
	}

	sql = sql + where + " ORDER BY  t1.create_time DESC"
	var totalRecords int64
	page := *queryParams.PageQuery.PageNum      // 当前页码
	pageSize := *queryParams.PageQuery.PageSize // 每页数据量

	// 计算偏移量
	offset := (page - 1) * pageSize
	var users = make([]fitness.User, 0)

	var res utils.Page[fitness.User]

	err := d.DB.Raw(sql).Offset(int(offset)).Limit(int(pageSize)).Find(&users).Error
	if err != nil {
		return res, err
	}
	// 获取总记录数
	err = d.DB.Model(&fitness.User{}).Count(&totalRecords).Error
	if err != nil {
		return res, err
	}
	//总数
	res.Total = totalRecords
	res.List = users
	return res, nil
}

// UpdateNickname 更新昵称
func (d *UserDao) UpdateNickname(id uint64, nickname *string) error {
	err := d.DB.Model(&fitness.User{}).
		Where("id = ? ", id).
		Update("nickname", nickname).Error
	return err
}

// UpdatePhone 更新手机号
func (d *UserDao) UpdatePhone(id uint64, phone *string) error {
	err := d.DB.Model(&fitness.User{}).
		Where("id = ? ", id).
		Update("phone", phone).Error
	return err
}
